//
//  CFSHttpRequest.swift
//  eval
//
//  Created by hengchengfei on 15/8/20.
//  Copyright © 2015年 chengfeisoft. All rights reserved.
//

import UIKit
import Alamofire
import ObjectMapper
import AdSupport

//public enum CFSHTTPStatusCode:Int {
//    case Success = 0
//    
//    case InternetError = 400
//    case UserNotPersmission = 101
//}

public enum CFSHTTPMethod:String {
    case GET,POST
}
public enum CFSHTTPParameterEncoding {
    case URL
    case JSON
    case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
}

public protocol CFSURLStringConvertable {
    var URLString:String{
        get
    }
}

extension String:CFSURLStringConvertable {
    public var URLString:String {
        return self
    }
}


/**
Creates a request using the shared manager instance for the specified method, URL string, parameters, and
parameter encoding.

- parameter method: The HTTP method.

- returns: The created request.
*/
public func request<T:Mappable>(
    method:CFSHTTPMethod,
    _ URLString:String,
    parameters:[String: AnyObject]? = nil,
    encoding:CFSHTTPParameterEncoding? = CFSHTTPParameterEncoding.URL,
    headers: [String: String]? = nil,
    success:((statusCode:Int?,data:NSDictionary?,model:T?) -> Void)?,
    failure:((statusCode:Int?,message:String) -> Void)?  = nil){
        var _method = Method.GET
        if method == CFSHTTPMethod.POST {
            _method = Method.POST
        }
        
        let url = URLString
        guard let _ = NSURL(string: url) else { return }
        
        // Create a shared URL cache
        let memoryCapacity = 500 * 1024 * 1024; // 500 MB
        let diskCapacity = 500 * 1024 * 1024; // 500 MB
        let cache = NSURLCache(memoryCapacity: memoryCapacity, diskCapacity: diskCapacity, diskPath: "shared_cache")
        
        // Create custom config
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders
        config.HTTPAdditionalHeaders = defaultHeaders
        config.requestCachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData //忽略本地缓存
        config.URLCache = cache
        config.timeoutIntervalForRequest = 20
        
        
        let manager = Alamofire.Manager(configuration: config)
        manager.request(_method, URLString, parameters: parameters, encoding: ParameterEncoding.URL, headers: headers).responseJSON(completionHandler: { response in
            
            //一定要加上这句http://stackoverflow.com/questions/30906607/about-alamofire-version-for-use-manager
            manager.session.invalidateAndCancel()

            if response.result.isSuccess {
                if let data = response.result.value as? NSDictionary {
                    if let code = data.valueForKey("code") as? Int {
                        let m = Mapper<T>().map(data)
                        if let s = success {
                            s(statusCode: code, data: data,model:m)
                        }
                    }else{
                        if let f = failure {
                            f(statusCode: nil, message: "返回的code为空")
                        }
                    }
                }
            }else{
                if let f = failure {
                     f(statusCode: nil, message: "\(response.result.debugDescription)\n\(response.response)")
                }
            }
        })
        
}
